The json library can parse JSON from either strings or files. The library parses JSON into a Python dictionary or list. It can also convert Python dictionaries or lists into JSON strings.
Take the following string containing JSON data:
In [1]:
import json
json_string = '{"first_name": "Guido", "last_name":"Rossum"}'
print(type(json_string))
parsed_json = json.loads(json_string)
print(parsed_json)
print(type(parsed_json))
In [3]:
print(parsed_json['first_name'], parsed_json['last_name'])
In [5]:
with open("random.json") as f:
parsed_json = json.loads(f.read())
print(parsed_json)
print(type(parsed_json))
In [23]:
py = {
'first_name': 'Guido',
'second_name': 'Rossum',
'titles': ['BDFL', 'Developer'],
}
data = json.dumps(d)
print(data)
print(type(data))
In [20]:
d = ["mayank", "Venky", "Prashant Bhandarkar"]
data = json.dumps(d)
print(data)
print(type(data))
In [26]:
import collections
py = str(py).replace("'", '"')
json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(str(py))
Out[26]:
In [44]:
from collections import OrderedDict
# OrderedDict as ordereddict
lnct_batch = """{
"es": ["Mukesh Bansal", "Kirti Khanna", "Jyoti Pancholi", "Nishant Shrivastava", "Gajendra Bandi"],
"cs": ["Amit Shrivastava"]
}"""
data = json.loads(lnct_batch, object_pairs_hook=OrderedDict)
print(json.dumps(data, indent=4))
In [40]:
data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)
print(json.dumps(data, indent=4))
In [9]:
import json
student = {"101":{"class":'V', "Name":'Rohit', "Roll_no":7},
"102":{"class":'V', "Name":'David', "Roll_no":8},
"103":{"class":'V', "Name":'Samiya', "Roll_no":12}}
print(json.dumps(student))
In [14]:
import json
student = {"101":{"Name":'Rohit',"Class":'V', "Roll_no":7},
"102":{"Name":'David',"Class":'V', "Roll_no":8},
"103":{"Name":'Samiya',"Class":'V', "Roll_no":12}}
print(json.dumps(student, sort_keys=True));
In [15]:
import json
tup1 = 'Red', 'Black', 'White';
print(json.dumps(tup1));
In [16]:
import json
list1 = [5, 12, 13, 14];
print(json.dumps(list1));
In [17]:
import json
string1 = 'Python and JSON';
print(json.dumps(string1));
In [18]:
import json
x = True;
print(json.dumps(x));
In [19]:
import json
json_data = '{"103": {"class": "V", "Name": "Samiya", "Roll_n": 12}, "102": {"class": "V", "Name": "David", "Roll_no": 8}, "101": {"class": "V", "Name": "Rohit", "Roll_no": 7}}';
print(json.loads(json_data));
In [ ]: